<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" layout="inline" :model="queryParams">
              <a-form-item label="题目" name="questionSetName">
                <a-input v-model:value="queryParams.templateName" placeholder="请输入题目" allow-clear
                         @blur="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="题型" name="questionType">
                <a-select v-model:value="queryParams.questionType" allow-clear
                          placeholder="选择题型" @change="handleQuery" :options="exam_question_type"
                          :field-names="{label: 'label', value: 'value'}" />
              </a-form-item>
              <a-form-item label="题目标签" name="tag">
                <a-select
                  v-model:value="queryParams.tag" :max-tag-count="2" mode="multiple"
                  allow-clear show-search placeholder="选择题目标签" :options="templateTagList"
                  :field-names="{ label: 'tagName', value: 'tagName' }" :virtual="false"
                  @change="handleQuery" style="width: 300px"
                >
                  <template #option="{ tagName, tagCount }">
                    <a-flex justify="space-between">
                      <span>{{ tagName }}</span>
                      <span style="color: #999">({{ tagCount }})</span>
                    </a-flex>
                  </template>
                </a-select>
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                         @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                         @click="resetQuery">重置
              </el-button>
              <el-button v-show="props.repoId" icon="Close" plain round type="danger" @click="handleClose">关闭
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>

    <a-card ref="cardRef" class="card-content" hoverable>
      <template #title>
        <el-row ref="headerRef" :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:question:add']" round icon="Plus" plain type="primary" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:question:edit']" round
                       :disabled="selection.selectedKeys.value.length === 0" icon="Edit"
                       plain type="success"
                       @click="handleUpdate()">批量修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:question:remove']" round plain
                       :disabled="selection.selectedKeys.value.length === 0"
                       icon="Delete"
                       type="danger"
                       @click="handleDelete()">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:question:export']" round icon="Download" plain type="warning"
                       @click="handleExport">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @resetQuery="resetQuery"
                         :columns="columns"></right-toolbar>
        </el-row>
      </template>
      <a-spin :spinning="loading" size="large">
        <el-auto-resizer>
          <template #default="{height, width}">
            <el-table-v2 :columns="columns" :data="questionList" row-key="templateId"
                         :height="tableHeight" :width="width" fixed>
              <template #header-cell="{ column }">
                <template v-if="column.dataKey === 'selection'">
                  <el-checkbox
                    :model-value="selection.isAllSelected.value"
                    :indeterminate="selection.isIndeterminate.value"
                    @change="selection.toggleAll"
                  />
                </template>
              </template>
              <template #cell="{column,rowData,rowIndex}">
                <template v-if="column.dataKey==='selection'">
                  <el-checkbox
                    :model-value="selection.selectedKeys.value.some(k=>k=== rowData.templateId)"
                    @change="selection.toggleSelection(rowData.templateId)"
                  />
                </template>
                <template v-if="column.dataKey === 'index'">
                  {{ rowIndex + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
                </template>
                <template v-if="column.dataKey === 'questionType'">
                  <dict-tag :options="exam_question_type" :value="rowData.questionType" />
                </template>
                <template v-else-if="column.dataKey === 'tag'">
                  <a-flex gap="small" justify="center" wrap="wrap">
                    <a-tag v-for="(item,index) in rowData.tag" :color="getAntTagColor(index)" :key="item">{{ item }}
                    </a-tag>
                  </a-flex>
                </template>
                <template v-else-if="column.dataKey === 'action'">
                  <el-tooltip content="修改" placement="top">
                    <el-button v-hasPermi="['exam:question:edit']" circle icon="Edit" plain type="primary"
                               @click="handleUpdate(rowData)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="删除" placement="top">
                    <el-button v-hasPermi="['exam:question:remove']" circle plain icon="Delete" type="danger"
                               @click="handleDelete(rowData)"></el-button>
                  </el-tooltip>
                </template>
              </template>
            </el-table-v2>
          </template>
        </el-auto-resizer>
      </a-spin>

    </a-card>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </a-card>
    <!-- 添加或修改题目对话框 -->
    <template-editor :drawer="drawer" :template-form-list="templateFormList" :repo-id="props.repoId"
                     @submit-success="getList" />
  </div>
</template>

<script lang="ts" name="Question" setup>
import { delQuestion, getQuestionList, pageQuestion } from '@/api/exam/template';
import { TemplateForm, TemplateQuery, TemplateVO, QuestionType, TemplateUpdateForm } from '@/api/exam/template/types';
import useSettingsStore from '@/store/modules/settings';
import { TagTypeEnum, TagVO } from '@/api/exam/tag/types';
import { listTag } from '@/api/exam/tag';
import { getAntTagColor } from '@/utils/tagColor';
import TemplateEditor from './info/edit.vue';
import { columns } from './data';
/*计算表格高度*/
import { useElTableHeight } from '@/utils/useElTableHeight';
import { RouteLocationNormalized } from 'vue-router';
import { AnswerVO } from '@/api/exam/answer/types';
import { cloneDeep } from 'lodash';
import { useSelection } from '@/utils/useSelection';


const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(0);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);

const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { exam_question_type } = toRefs<any>(proxy?.useDict('exam_question_type'));

const questionList = ref<TemplateVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const questionFormRef = ref<ElFormInstance>();
const templateTagList = ref<TagVO[]>([]);

const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});

interface Props {
  repoId?: any;
}

const props = withDefaults(defineProps<Props>(), {
  repoId: null
});

const currentRepoId = ref(props.repoId);

const initFormData: TemplateForm = {
  templateId: undefined,
  repoId: undefined,
  questionType: undefined,
  tag: undefined,
  difficulty: undefined,
  orderNum: undefined,
  templateName: undefined,
  answer: undefined,
  score: undefined,
  remark: undefined
};
const data = reactive<PageData<TemplateForm, TemplateQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    templateId: undefined,
    repoId: undefined,
    questionType: undefined,
    tag: undefined,
    orderNum: undefined,
    templateName: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询题目列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.repoId = currentRepoId.value;
  const res = await pageQuestion(queryParams.value);
  questionList.value = res.rows;
  console.log(questionList.value);
  total.value = res.total;
  loading.value = false;
};

// 使用多选逻辑
const selection = useSelection(
  questionList, 'templateId' // 指定唯一键字段
);

/*查询题目标签列表 */
const getTemplateTagList = async () => {
  const res = await listTag({ tagType: TagTypeEnum.TemplateType });
  templateTagList.value = res.data;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  questionFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.tag = undefined;
  handleQuery();
};
const handleClose = () => {
  const obj: RouteLocationNormalized = {
    path: '/repo/list',
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined
  };
  proxy?.$tab.closeOpenPage(obj);
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  templateFormList.value = [];
  drawer.visible = true;
  drawer.title = '添加题目';
};
const templateFormList = ref([]);
/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  templateFormList.value = [];
  const _questionIds = row?.templateId || selection.selectedKeys.value;
  const res = await getQuestionList(_questionIds);
  Object.assign(templateFormList.value, res.data);
  drawer.visible = true;
  drawer.title = '修改题目';
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const _questionIds = row?.templateId || selection.selectedKeys.value;
  let length = row ? 1 : selection.selectedKeys.value.length;
  await proxy?.$modal.modal('删除数据', '确认删除这 ' + `<font color="red"> ${length}</font>` + ' 条数据吗？');
  await delQuestion(_questionIds);
  proxy?.$modal.notifySuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('exam/question/export', {
    ...queryParams.value
  }, `template_${new Date().getTime()}.xlsx`);
};


onMounted(async () => {
  await getTemplateTagList();
  await getList();
});
</script>
<style lang="scss">

</style>


